﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using DevFX.Infrastructure.ViewUtility;
using DevFX.Infrastructure.Interfaces;
using DevFX.Data.ServiceProvider;
using System.Collections.ObjectModel;
using DevFX.Infrastructure.Commons;
using Microsoft.Practices.Composite.Modularity;

namespace DevFX.Modules.Passport.UserModule.ViewModule
{
    public class UserViewModel : ViewModelBase, IUserViewModel
    {
        private bool isBusy = false;

        public UserViewModel()
        {
            Users = new ObservableCollection<User>();
            LoadAsync();
        }

        public bool IsBusy
        {
            get { return isBusy; }
            private set
            {
                if (isBusy != value)
                {
                    isBusy = value;
                    FirePropertyChanged("IsBusy");
                }
            }
        }

        public ObservableCollection<User> Users { get; protected set; }

        #region IUsersViewModel 成员

        public void LoadAsync()
        {
            IsBusy = true;
            UserServiceClient client = WcfServiceClientFactory<UserServiceClient, IUserService>.CreateServiceClient(new Uri("http://localhost:1601/UserService.svc"));
            client.GetUsersAsync();
            client.GetUsersCompleted += new EventHandler<GetUsersCompletedEventArgs>(client_GetUsersCompleted);
        }

        #endregion

        #region IViewModel 成员

        public IModel Model
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        #endregion

        private void client_GetUsersCompleted(object sender, GetUsersCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                Users.Clear();

                foreach (var user in e.Result)
                {
                    Users.Add(user);
                }
            }
            IsBusy = false;
        }
    }
}
